package com.demo.service.deepseek;

import com.demo.config.DeepSeekConfig;
import com.demo.exception.ApiException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class DeepSeekChatService implements DeepSeekService{
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
    private final DeepSeekConfig config;

    public DeepSeekChatService(OkHttpClient client, DeepSeekConfig config) {
        this.client = client;
        this.objectMapper = new ObjectMapper();
        this.config = config;
    }

    @Override
    public String chatCompletion(String prompt) throws ApiException {
        try{
            Request request = buildRequest(prompt);
            log.debug("Sending request to: {}", config.getUrl());
            log.debug("Request headers: {}", request.headers());

            Response response = client.newCall(request).execute();
            log.debug("Response code: {}", response.code());

            return processResponse(response);  // 注意这里修改了参数
        } catch(IOException e){
            log.error("API请求失败: {}", e.getMessage());
            // 修改这一行调用方式：
            throw new ApiException("API_ERROR", "DeepSeek服务调用失败", e);
        }
    }

    private Request buildRequest(String prompt) throws IOException {
        JsonNode messagesNode = objectMapper.createArrayNode()
                .add(objectMapper.createObjectNode()
                        .put("role", "user")
                        .put("content", prompt));

        JsonNode requestBody = objectMapper.createObjectNode()
                .put("model", "deepseek-chat")
                .set("messages", messagesNode);

        String jsonBody = requestBody.toString();

        return new Request.Builder()
                .url(config.getUrl())
                .addHeader("Authorization", "Bearer " + config.getKey())
                .post(RequestBody.create(MediaType.get("application/json"), jsonBody))
                .build();
    }
    private String processResponse(Response response) throws IOException{
        if(!response.isSuccessful()){
            throw new IOException("HTTP错误: " + response.code());
        }
        JsonNode rootNode = objectMapper.readTree(response.body().byteStream());
        return rootNode.path("choices")
                .get(0)
                .path("message")
                .path("content")
                .asText();
    }
}